package com.fs.base.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fs.base.param.SysConstant;
import com.fs.base.pojo.User;
import com.fs.base.service.RoleService;
import com.fs.base.utils.ApplicationUtils;
import com.fs.base.vo.DataGrid;
import com.fs.base.vo.LoginUser;
import com.fs.base.vo.SysPath;

/**
 * @author TiddlerCJ
 * @desc 用户登录登出
 */
@Controller
@RequestMapping(SysPath.BACK_PATH)
public class LoginController {
	@Autowired  RoleService roleService;
	
	@GetMapping("")
	public String console(HttpServletRequest request){
		return SysPath.BACK_PATH.concat("/console");
	}
	/**
	 * 获取登陆页面需要的相关数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/data")
	public Object getConsoleData(){
		Map<String,Integer> data = new HashMap<String,Integer>();
		return data;
	}
	
	@GetMapping("/login")
	public String loginGet(HttpSession session){
		return logout(session);
	}
	
	@GetMapping("/logout")
	public String logout(HttpSession session){
		session.removeAttribute(SysConstant.SESSION_CONSOLE_USER);
		session.removeAttribute(SysConstant.SESSION_CONSOLE_MENU);
		session.removeAttribute(SysConstant.SESSION_CONSOLE_MENU_MOTION);
		return SysPath.BACK_PATH.concat("/login");
	}
	
	@ResponseBody
	@PostMapping("/login")
	public LoginUser loginPost(String loginAccount,String  loginPwd,HttpSession session){
		User user = new User(loginAccount, loginPwd);
		LoginUser uVo = roleService.login(user); 
		uVo.setLoginIp(ApplicationUtils.getRemoteHost());
		uVo.setIsSysAdm(user.isSysAdm());
		if(uVo.getLoginStatus()){
			session.setAttribute(SysConstant.SESSION_CONSOLE_USER, uVo);
			session.setAttribute(SysConstant.SESSION_CONSOLE_MENU, JSON.toJSON(DataGrid.treeBuilder(uVo.getMenus(), "id", "parentId")));
			session.setAttribute(SysConstant.SESSION_CONSOLE_MENU_MOTION, JSON.toJSON(uVo.getMotions()));
		}
		return uVo;
	}
}
